/**
 * Title :	jFamilyTree generator
 * Description: jFamilyTree generator
 * Version:	provider
 * Copyright (c) 2001-2008
 * Terms of use:see license agreement at http://treebolic.sourceforge.net/en/license.htm
 * Author: Bernard Bou
 * Company: bsys
 */
package jFamilyTree.generator.domtree;

import javax.swing.JTree;
import javax.swing.tree.TreeCellRenderer;
import javax.swing.tree.TreeModel;
import javax.swing.tree.TreePath;
import javax.swing.tree.TreeSelectionModel;

import org.w3c.dom.Document;

import jFamilyTree.Messages;

/**
 * DOM tree view
 * 
 * @author Bernard Bou
 */
public class DomTreeView extends JTree
{
	private static final long serialVersionUID = 1L;

	// C O N S T R U C T O R

	/**
	 * Constructor
	 */
	public DomTreeView(TreeCellRenderer thisRenderer)
	{
		super((TreeModel) null);

		setToggleClickCount(1);
		setScrollsOnExpand(true);
		setDragEnabled(false);
		setEditable(false);
		setToolTipText(Messages.getString("DomTreeView.0")); //$NON-NLS-1$
		setRowHeight(17);
		setShowsRootHandles(true);
		putClientProperty("JTree.lineStyle", "Horizontal"); //$NON-NLS-1$ //$NON-NLS-2$
		getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);

		// renderer
		setCellRenderer(thisRenderer == null ? new Renderer() : thisRenderer);
	}

	// M O D E L

	/**
	 * Set model from document
	 * 
	 * @param thisDocument
	 *        document
	 */
	public void setDocument(Document thisDocument)
	{
		if (thisDocument == null)
		{
			setModel(null);
		}
		else
		{
			// set
			TreeModel thisModel = new TreeModelAdapter(thisDocument, null, false);
			setModel(thisModel);

			// visibility
			expandAll();
		}
	}

	// E X P A N D

	/**
	 * Expand all
	 */
	public void expandAll()
	{
		Object thisRoot = getModel().getRoot();
		if (thisRoot == null)
		{
			return;
		}
		TreePath thisPath = new TreePath(thisRoot);
		expandAll(thisPath);
	}

	/**
	 * Expand all subtree
	 * 
	 * @param thisPath
	 *        tree path
	 */
	public void expandAll(TreePath thisPath)
	{
		// this
		expandPath(thisPath);

		// recursive call for each child
		Object thisNode = thisPath.getLastPathComponent();
		int thisCount = getModel().getChildCount(thisNode);
		for (int i = 0; i < thisCount; i++)
			expandAll(thisPath.pathByAddingChild(getModel().getChild(thisNode, i)));
	}
}
